﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using KLS.PPDS.ApplicationService.Manager;
using KLS.PPDS.Core.Entity;
using KLS.PPDS.Utilities;
using KLS.PPDS.Utilities.Enums;
using KLS.PPDS.Utility;
using KLS.PPDS.Web.Models;
using KLS.PPDS.Resources;
using System.Text;

namespace KLS.PPDS.Web.Controllers.Login
{
    /// <summary>
    /// loginController.cs
    /// </summary>
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index(LogOnModel model)
        {
         //   CommonTask.SetCulture("da-DK");
            Session.Clear();
            Session.Abandon();
            if (CommonSession.UserId>0)
            {
                
                return View("~/Views/Login/Login.aspx", model);
            }
            
            return View("~/Views/Login/Login.aspx", model);
        }

        public ActionResult Logout(LogOnModel model)
        {
            LogManager.Log(new Log(), ActionName.Logoff, CommonSession.UserName + " has Logout from the System.");
            Session.Clear();
            Session.Abandon();
            FormsAuthentication.SignOut();
            return View("~/Views/Login/Login.aspx",model);
        }
        
        ///<summary>
        /// Login action
        ///</summary>
        ///<param name="model"></param>
        ///<returns></returns>
        [HttpPost]
        public  ActionResult OnLogin(LogOnModel model)
        {

            var usr = UserManager.Get(model.UserName);

            if (usr != null && usr.Id > 0)
            {

                if (usr.Password == model.Password)
                {

                    SetUserToSession(usr);
                    FormsAuthentication.RedirectFromLoginPage(usr.UserName, false);
                    LogManager.Log(new Log(), ActionName.Login, CommonSession.UserName + " has LogIn to the System.");
                    return RedirectToAction("Index", "Home");
                }
                
                 
            }
            if (!(string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.Password)))
            {
                model.ErrorMessage = CommonMessage.WrongUserNamePassword;
            }
            

            model.Password = string.Empty;
            return View("~/Views/Login/Login.aspx", model);
        }

        ///<summary>
        /// Forget password action
        ///</summary>
        ///<param name="userName"></param>
        ///<returns></returns>
        [HttpPost]
        public ActionResult ForgetPassword(string userName)
        {
            var message = CommonString.InvalidUser;
            var sendMail = false;
            if (userName.ToLower() != "admin")
            {
                var user = UserManager.Get(userName);

                if (user != null && user.Id > 0)
                {
                    var subject = CommonString.MailSubjectForgetPassword;
                    var body = new StringBuilder();
                    var newLine = CommonTask.MailBodyNewLine;
                    body.Append(CommonTask.MailBodyStart) ;
                    body.Append(CommonString.MailBodyForgetPassword);
                    body.Append(newLine);
                    body.Append(newLine);
                    body.Append(CommonString.UserName + " : ");
                    body.Append(user.UserName);
                    body.Append(newLine);
                    body.Append(CommonString.Password+ " : ");
                    body.Append(user.Password);
                    body.Append(CommonTask.MailBodyEnd);
                    CommonTask.SendMail(WebConfig.DefaultEmailSender, user.UserName, subject.ToString(), body.ToString());
                    message = CommonString.MailSendToForgetPasswordUser;
                    sendMail = true;
                }
            }
            else
            {
                message = "";
            }
            return new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,

                Data = new
                {
                    Message = message,                    
                    Result = sendMail
                }
            };
            
        }

        /// <summary>
        /// Set usr to session
        /// </summary>
        /// <param name="usr"></param>
        void SetUserToSession(User usr)
        {
            Session["LoggedIn"] = true;
            
            CommonSession.UserId = usr.Id;
            CommonSession.UserName = usr.UserName;
            CommonSession.CompanyName = string.Empty;

            CommonSession.CompanyId = 0;

            if (usr.CompanyId.HasValue) 
            {
                CommonSession.CompanyId = usr.CompanyId.Value;
                CommonSession.CompanyName = usr.Company.CompanyName;
            }
            

            if (usr.Language != null && ! String.IsNullOrEmpty( usr.Language.Code) )
            {
                CommonSession.Language = usr.Language.Code;
            }
            else 
            {
                CommonSession.Language = WebConfig.DefaultLanguage;
            }

            CommonSession.IsUserSuperAdminOrGraphic = false;
            CommonSession.IsUserSuperAdmin = false;
            CommonSession.IsUserEditor = false;
            CommonSession.IsUserGraphicsDesigner = false;
            CommonSession.IsUserJournalist = false;
            //is superadmin
            if (usr.Role.RoleName == CommonConstant.Superadmin)
            {
                CommonSession.IsUserSuperAdmin = true;
                CommonSession.IsUserSuperAdminOrGraphic = true;
            }

            //editor
            if (usr.Role.RoleName == CommonConstant.Editor)
            {
                CommonSession.IsUserEditor = true;
            }

            //is graphics
            if (usr.Role.RoleName == CommonConstant.Graphics)
            {
                CommonSession.IsUserSuperAdminOrGraphic = true;
                CommonSession.IsUserGraphicsDesigner = true;
            }          

            //Journalist
            if (usr.Role.RoleName == CommonConstant.Journalist)
            {
                CommonSession.IsUserJournalist = true;
            }


            //Superadmin & Graphics does not belong to any company
            if (usr.Role.RoleName == CommonConstant.Superadmin || usr.Role.RoleName == CommonConstant.Graphics)
            {                
                CommonSession.CompanyId = 0;
                CommonSession.CompanyName = string.Empty;
            }
         
        }
    }
}
